﻿using FileTransSystem.Helper;
using MaterialDesignThemes.Wpf;
using Panuon.UI.Silver;
using System;
using System.Data;
using System.Data.SQLite;
using System.Windows;

namespace FileTransSystem
{
    /// <summary>
    /// RegisterWindow.xaml 的交互逻辑
    /// </summary>
    public partial class RegisterWindow : WindowX
    {
        public SQLiteConnection SqLiteConnection;
        private Window window;
        private string inviteCode;

        public RegisterWindow(Window window)
        {
            InitializeComponent();
            this.window = window;
            inviteCode = "112233";
        }

        public async void MessageTips(string message, object sender, RoutedEventArgs e, string Identifier)
        {
            var MessageDialog = new MessageDialog
            {
                Message = { Text = message }
            };
            await DialogHost.Show(MessageDialog, Identifier);
        }

        private void ButtonRegister_OnClick(object sender, RoutedEventArgs e)
        {
            SqLiteConnection = GetSqlConnection.Connect();
            SQLiteCommand tmpCommand = DatabaseHelper.CreateCommand(SqLiteConnection,
                "select count(*) from userAccount where account=@account",
                DatabaseHelper.CreateParameter("@account", DbType.String, TextBoxAccount.Text));


            if (string.IsNullOrWhiteSpace(TextBoxAccount.Text))
            {
                MessageTips("请输入用户名！", sender, e, "RegisterDialog");
            }
            else if (string.IsNullOrWhiteSpace(TextBoxPassword.Password))
            {
                MessageTips("请输入密码！", sender, e, "RegisterDialog");
            }
            else if (TextBoxPassword.Password.Length < 5 || TextBoxPassword.Password.Length > 20)
            {
                MessageTips("密码长度在5-20位之间！", sender, e, "RegisterDialog");
            }
            else if (0 != Convert.ToInt32(tmpCommand.ExecuteScalar()))
            {
                MessageTips("用户名已存在！", sender, e, "RegisterDialog");
            }
            else
            {
                SQLiteParameter[] parameters = new SQLiteParameter[6];
                string salt = Guid.NewGuid().ToString();
                parameters[0] = DatabaseHelper.CreateParameter("@account", DbType.String, TextBoxAccount.Text);

                parameters[1] = DatabaseHelper.CreateParameter("@password", DbType.String,
                    EncryptPassword(TextBoxPassword.Password, salt));
                parameters[2] = DatabaseHelper.CreateParameter("@salt", DbType.String, salt);
                parameters[3] = DatabaseHelper.CreateParameter("@profile", DbType.String, TextBoxProfile.Text);
                parameters[4] =
                    DatabaseHelper.CreateParameter("@sex", DbType.String, ComboBoxSex.SelectionBoxItem.ToString());
                parameters[5] =
                    DatabaseHelper.CreateParameter("@isAdmin", DbType.Boolean,
                        TextBoxInvitationCode.Text.Equals(inviteCode));
                DatabaseHelper.CreateCommand(SqLiteConnection,
                    "insert into userAccount(account,password,salt,profile,sex,isAdmin) values" +
                    "(@account,@password,@salt,@profile,@sex,@isAdmin)", parameters).ExecuteNonQuery();
                MessageTips("注册成功！身份：" + (TextBoxInvitationCode.Text.Equals(inviteCode) ? "管理员" : "用户"), sender, e,
                    "SuccessDialog");
                GetSqlConnection.CloseConnect();
            }
        }

        private void ButtonCancel_OnClick(object sender, RoutedEventArgs e)
        {
            this.Close();
            window.Visibility = Visibility.Visible;
        }


        //使用加盐哈希生成密码
        private string EncryptPassword(string password, string salt)
        {
            byte[] passwordAndSaltBytes = System.Text.Encoding.UTF8.GetBytes(password + salt);
            byte[] hashBytes = new System.Security.Cryptography.SHA256Managed().ComputeHash(passwordAndSaltBytes);
            string hashString = Convert.ToBase64String(hashBytes);
            return hashString;
        }

        private void DialogHost_OnDialogClosing(object sender, DialogClosingEventArgs eventargs)
        {
            this.Close();
            window.Visibility = Visibility.Visible;
        }
    }
}